package com.anysoft.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;

import com.blankj.utilcode.util.ToastUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by wwq on 2017/3/8.
 */

public class BitmapUtils {

    public static Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
                //System.out.println("bitmap存在");
            }
        } catch (Exception e) {
            //System.out.println("bitmap不存在");
        }
        return bitmap;
    }

    /**
     * 把两个Bitmap合成一个Bitmap
     *
     * @param backgroundBitmap 背景Bitmap
     * @param iconBitmap       图标Bitmap，将显示在背景Bitmap的中央
     * @return 合成后的Bitmap
     */
    public static Bitmap compoundBitmap(Bitmap backgroundBitmap, Bitmap iconBitmap) {
        int qrcodeWidth = backgroundBitmap.getWidth();
        int qrcodeHeight = backgroundBitmap.getHeight();
        int iconX = (qrcodeWidth - iconBitmap.getWidth()) / 2;
        int iconY = (qrcodeHeight - iconBitmap.getHeight()) / 2;

        // 创建一个新的空的Bitmap
        Bitmap compoundBitmap = Bitmap.createBitmap(qrcodeWidth, qrcodeHeight, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(compoundBitmap);
        canvas.drawBitmap(backgroundBitmap, 0, 0, null);    // 在 0，0坐标开始画入bg
        canvas.drawBitmap(iconBitmap, iconX, iconY, null);    // 把icon画在bg的中央
        canvas.save(Canvas.ALL_SAVE_FLAG);                    // 保存
        canvas.restore();                                    // 存储
        return compoundBitmap;
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
                .getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

    public static boolean isNullOrRecycled(Bitmap bitmap) {
        if (bitmap == null || bitmap.isRecycled()) {
            return true;
        }
        return false;
    }

    /**
     * 保存bitmap到本地
     *
     * @param bitName
     * @param mBitmap
     */
    public static void saveBitmap(String bitName, Bitmap mBitmap) {
        if(TextUtils.isEmpty(bitName) || BitmapUtils.isNullOrRecycled(mBitmap)){
            return;
        }
        if (!DiskUtils.isExistsDir(DiskUtils.CACHE_IMAGE_PATH)){
            ToastUtils.showShort("保存图片失败");
            return;
        }
        File f = new File(DiskUtils.CACHE_IMAGE_PATH + bitName + ".png");
        try {
            f.createNewFile();
        } catch (IOException e) {

        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储图片到系统图库
     *
     * @param context
     * @param bmp
     */
    public static void saveImageToGallery(Context context, Bitmap bmp) throws Exception {
        // 首先保存图片
        File appDir = new File(DiskUtils.CACHE_IMAGE_PATH);
        String path = "";
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        path = file.getPath();

        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 0, fos);
        fos.flush();
        fos.close();

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }

    /**
     *base64编码字符集转化成图片文件。
     * @param base64Str
     * @return 是否成功
     */
    public static boolean base64ToFile(String base64Str,String fileName){
        byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if(data[i] < 0){
                //调整异常数据
                data[i] += 256;
            }
        }
        File appDir = new File(DiskUtils.CACHE_IMAGE_PATH);
        String path = "";
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        path = file.getPath();
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }

    }

    /**
     * bitmap转为base64
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
